package com.glory.wxelectricitypda.activity;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.wxelectricitypda.R;
import com.glory.wxelectricitypda.adapter.LockersTakenOffShelvesAdapter;
import com.glory.wxelectricitypda.base.BaseDialogActivity;
import com.glory.wxelectricitypda.bean.LockersTakenOffShelvesBean;
import com.glory.wxelectricitypda.bean.LotBean;
import com.glory.wxelectricitypda.bean.ResponseBean;
import com.glory.wxelectricitypda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_CommonCallback;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_TextCallback;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

public class LockersTakenOffShelvesActivity extends BaseDialogActivity {


    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.eqpID)
    FreeUI_ClearEditText eqpID;
    @BindView(R.id.lotID)
    FreeUI_ClearEditText lotID;
    @BindView(R.id.useID)
    FreeUI_ClearEditText useID;
    @BindView(R.id.recycler)
    RecyclerView recycler;
    @BindView(R.id.flStepName)
    FrameLayout flStepName;
    @BindView(R.id.tvStepName)
    TextView tvStepName;
    @BindView(R.id.ivStepName)
    ImageView ivStepName;
    @BindView(R.id.flType)
    FrameLayout flType;
    @BindView(R.id.tvType)
    TextView tvType;
    @BindView(R.id.ivType)
    ImageView ivType;
    @BindView(R.id.flEqpId)
    FrameLayout flEqpId;
    @BindView(R.id.tvEqpId)
    TextView tvEqpId;
    @BindView(R.id.autoCompleteTextView)
    AutoCompleteTextView autoCompleteTextView;
    @BindView(R.id.ivEqpId)
    ImageView ivEqpId;

    private LockersTakenOffShelvesAdapter adapter;
    private FreeUI_GeneralPop mStepNamePop;
    private ArrayList<String> stepNameList = new ArrayList<>();
    private FreeUI_GeneralPop mTypePop;
    private FreeUI_GeneralPop mEqpIdPop;
//    private PopupWindow mEqpIdPop;
    private ArrayList<String> EqpIdList = new ArrayList<>();
    private ArrayList<String> typeList = new ArrayList<>();
    private Map<String,String> typeIDMap = new HashMap<>();

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_lockers_taken_off_shelves;
    }

    @Override
    protected void initView() {
        freeUI_titleView.setTitle("储物柜下架");
        freeUI_titleView.setRightListener("下架", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (useID.getText().toString().isEmpty()){
                    showToast("请扫描工号！",false);
                    return;
                }
                if (lotID.getText().toString().isEmpty()){
                    showToast("请扫描批次号！",false);
                    return;
                }
                if (eqpID.getText().toString().isEmpty()){
                    showToast("请扫描库房号！",false);
                    return;
                }
                if (tvEqpId.getText().toString().isEmpty()){
                    showToast("请扫描设备！",false);
                    return;
                }
                if (tvType.getText().toString().isEmpty()){
                    showToast("请选择领用类型！",false);
                    return;
                }
                submit();
            }
        });

        recycler.setLayoutManager(new LinearLayoutManager(LockersTakenOffShelvesActivity.this));
        recycler.setItemAnimator(new DefaultItemAnimator());
        recycler.addItemDecoration(new DividerItemDecoration(LockersTakenOffShelvesActivity.this, 1));
        adapter = new LockersTakenOffShelvesAdapter(null);
        adapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        adapter.isFirstOnly(true);
        recycler.setAdapter(adapter);
    }

    @Override
    protected void initData() {

        getMlotAppLycreate();
        getScrapcodeList();

        initEdit(lotID,s->{
            if (useID.getText().toString().isEmpty()){
                showToast("请扫描工号！",false);
                lotID.setText("");
                return;
            }
            queryLotID();
            queryStepName();
        });

        flStepName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mStepNamePop != null) {
                    if (mStepNamePop.isShowing()) {
                        mStepNamePop.dismiss();
                    }
                } else {
                    mStepNamePop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flStepName.getWidth(), stepNameList, ivStepName, new FreeUI_TextCallback() {
                        @Override
                        public void onSuccess(String s) {
                            tvStepName.setText(s);
                            queryEtEqpId();
                        }
                    });
                }
                FreeApi_PopUtils.setArrowShow(ivStepName);
                mStepNamePop.showAsDropDown(flStepName, 0, 0);
            }
        });
        flType.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mTypePop != null) {
                    if (mTypePop.isShowing()) {
                        mTypePop.dismiss();
                    }
                } else {
                    mTypePop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flType.getWidth(), typeList, ivType, new FreeUI_TextCallback() {
                        @Override
                        public void onSuccess(String s) {
                            tvType.setText(s);
                        }
                    });
                }

                FreeApi_PopUtils.setArrowShow(ivType);
                mTypePop.showAsDropDown(flType, 0, 0);
            }
        });


        flEqpId.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

//                if (mEqpIdPop != null) {
//                    if (mEqpIdPop.isShowing()) {
//                        mEqpIdPop.dismiss();
//                    }
//                } else {
                    mEqpIdPop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flEqpId.getWidth(), EqpIdList, ivEqpId, new FreeUI_TextCallback() {
                        @Override
                        public void onSuccess(String s) {
                            tvEqpId.setText(s);
                        }
                    });
//                }

                FreeApi_PopUtils.setArrowShow(ivEqpId);
                mEqpIdPop.showAsDropDown(flEqpId, 0, 0);
            }
        });


//        // 创建适配器
//        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, EqpIdList);
//
//        // 设置适配器到AutoCompleteTextView
//        autoCompleteTextView.setAdapter(adapter);
//
//        // 设置触发下拉框的点击事件
//        flEqpId.setOnClickListener(v -> autoCompleteTextView.showDropDown());
//
//        // 设置模糊查询功能
//        autoCompleteTextView.setThreshold(1);
//
//        // 设置选中项的监听事件
//        autoCompleteTextView.setOnItemClickListener((parent, view, position, id) -> {
//            String selectedEqpId = (String) parent.getItemAtPosition(position);
//            // 在TextView上显示选中的设备ID
//            tvEqpId.setText(selectedEqpId);
//        });

    }



    private void queryStepName(){
        JSONObject jsonObject = new JSONObject();
        JSONObject jsonObject1 = new JSONObject();
        try {
            jsonObject1.put("LOTID", lotID.getText().toString());
            jsonObject1.put("ACTIONTYPE", "GETLOTINFO");
            jsonObject.put("Data", jsonObject1);
            jsonObject.put("MessageName", "EUIT.EUITLOTQUERY");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        NetUtils.requestPostMesForwardUtils(jsonObject, this, new FreeUI_DialogEntityCallBack<ResponseBean<LotBean>>(
                new TypeToken<ResponseBean<LotBean>>() {
                }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<ResponseBean<LotBean>> response) {
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    tvStepName.setText(response.body().getBody().getLOT().getSTEPNAME());
                    queryEtEqpId();
                }
            }

            @Override
            public void onError(Response<ResponseBean<LotBean>> response) {
                super.onError(response);
                loadError(response.getException(), "GETLOTINFO");
            }
        });
    }

    private void getScrapcodeList() {
        JSONObject map = new JSONObject();
        JSONObject jsonObject = new JSONObject();
        try {
            map.put("ACTIONTYPE", "GETBYREFNAME");
            map.put("REFNAME", "SBE_MLOT_APPOINTMENT_MA_TYPE");
            jsonObject.put("Data",map);
            jsonObject.put("MessageName","EUIT.EuitADUREFLISTHANDLER");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        NetUtils.requestPostMesForwardUtils(jsonObject,this, new FreeUI_DialogEntityCallBack<ResponseBean<LotBean>>(
                new TypeToken<ResponseBean<LotBean>>() {
                }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<ResponseBean<LotBean>> response) {
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    for (LotBean.AdurefBean adurefBean : response.body().getBody().getADUREFLIST()) {
                        typeIDMap.put(adurefBean.getTEXT(),adurefBean.getKEYID());
                        typeList.add(adurefBean.getTEXT());
                    }
                }
            }

            @Override
            public void onError(Response<ResponseBean<LotBean>> response) {
                super.onError(response);
                loadError(response.getException(), "ADUREFLISTHANDLER");
            }
        });

    }

    private void getMlotAppLycreate() {
        stepNameList.clear();
        JSONObject jsonObject = new JSONObject();
        JSONObject jsonObject1 = new JSONObject();
        try {
            jsonObject1.put("ACTIONTYPE", "ACTIVESTEP");
            jsonObject.put("Data", jsonObject1);
            jsonObject.put("MessageName", "EUIT.MLOTAPPLYCREATE");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        NetUtils.requestPostMesForwardUtils(jsonObject, this, new FreeUI_DialogEntityCallBack<ResponseBean<LotBean>>(
                new TypeToken<ResponseBean<LotBean>>() {
                }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<ResponseBean<LotBean>> response) {
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    for (LotBean.StepBean stepBean : response.body().getBody().getSTEPLIST()) {
                        stepNameList.add(stepBean.getNAME());
                    }
                } else {
                    finish();
                }
            }

            @Override
            public void onError(Response<ResponseBean<LotBean>> response) {
                super.onError(response);
                loadError(response.getException(), "ACTIVESTEP");
                finish();
            }
        });
    }

    private void queryLotID(){

        JSONObject map = new JSONObject();
        JSONObject jsonObject = new JSONObject();
        try {
            map.put("ACTIONTYPE", "ACTIONAPPLYOUTQUERY");
            map.put("LOTID", lotID.getText().toString());
            jsonObject.put("Data", map);
            jsonObject.put("MessageName", "EUIT.MLOTAPPLYOUT");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        NetUtils.requestPostMesForwardUtils(jsonObject, this, new FreeUI_DialogEntityCallBack<ResponseBean<LockersTakenOffShelvesBean>>(
                new TypeToken<ResponseBean<LockersTakenOffShelvesBean>>() {
                }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<ResponseBean<LockersTakenOffShelvesBean>> response) {
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    adapter.setNewData(response.body().getBody().getMATLIST());

                }
            }

            @Override
            public void onError(Response<ResponseBean<LockersTakenOffShelvesBean>> response) {
                super.onError(response);
                loadError(response.getException(), "MLOTAPPLYOUT");
            }
        });

    }

    private void queryEtEqpId(){
        if (lotID.getText().toString().isEmpty()){
            showToast("请扫描批次号！",false);
            return;
        }
        EqpIdList.clear();
        JSONObject map = new JSONObject();
        JSONObject jsonObject = new JSONObject();
        try {
            map.put("ACTIONTYPE", "QUERYEQP");
            map.put("LOTID", lotID.getText().toString());
            map.put("STEPNAME", tvStepName.getText().toString());
            jsonObject.put("Data", map);
            jsonObject.put("MessageName", "EUIT.MLOTAPPLYCREATE");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        NetUtils.requestPostMesForwardUtils(jsonObject, this, new FreeUI_DialogEntityCallBack<ResponseBean<LockersTakenOffShelvesBean>>(
                new TypeToken<ResponseBean<LockersTakenOffShelvesBean>>() {
                }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<ResponseBean<LockersTakenOffShelvesBean>> response) {
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    for (LockersTakenOffShelvesBean.EQPLISTDTO bean:response.body().getBody().getEQPLIST()) {
                        EqpIdList.add(bean.getEQUIPMENTID());
                    }
                }
            }

            @Override
            public void onError(Response<ResponseBean<LockersTakenOffShelvesBean>> response) {
                super.onError(response);
                loadError(response.getException(), "MLOTAPPLYCREATE");
            }
        });



    }


    private void submit(){

        JSONObject map = new JSONObject();
        JSONObject mlotAppointmentObject = new JSONObject();
        JSONObject jsonObject = new JSONObject();
        try {
            map.put("ACTIONTYPE", "ACTIONAPPLYOUT");
            map.put("LOTID", lotID.getText().toString());
            map.put("EQPID", eqpID.getText().toString());
            mlotAppointmentObject.put("LOTID", lotID.getText().toString());
            mlotAppointmentObject.put("STEPNAME", tvStepName.getText().toString());
            mlotAppointmentObject.put("EQUIPMENTID", tvEqpId.getText().toString());
            mlotAppointmentObject.put("MATTYPE", adapter.getData().get(0).getMATERIALTYPE());
            mlotAppointmentObject.put("MATYPE", typeIDMap.get(tvType.getText().toString()));
            mlotAppointmentObject.put("CLASS", "MAT");
            mlotAppointmentObject.put("MAINQTY", adapter.getData().get(0).getMAINQTY());
            mlotAppointmentObject.put("MLOTMAINQTY", adapter.getData().get(0).getMAINQTY());
            mlotAppointmentObject.put("MATERIALNAME", adapter.getData().get(0).getMATERIALNAME());
            map.put("MLOTAPPOINTMENT", mlotAppointmentObject);
            map.put("CURRENTOUTLIST", new JSONArray(new Gson().toJson(adapter.getData())));
            jsonObject.put("Data", map);
            jsonObject.put("MessageName", "EUIT.MLOTAPPLYOUT");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        NetUtils.requestPostMesForwardUtils(jsonObject, this, new FreeUI_DialogEntityCallBack<ResponseBean<LockersTakenOffShelvesBean>>(
                new TypeToken<ResponseBean<LockersTakenOffShelvesBean>>() {
                }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<ResponseBean<LockersTakenOffShelvesBean>> response) {
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    if (!response.body().getBody().getSTORAGEID().isEmpty()){
                        FreeApi_DialogUtils.getConfirmDialog(LockersTakenOffShelvesActivity.this, "确定","发料成功柜子号："+response.body().getBody().getSTORAGEID(), new FreeUI_CommonCallback() {
                            @Override
                            public void onSuccess() {

                                showToast("下架成功", true);
                                lotID.setText("");
                                tvStepName.setText("");
                                tvEqpId.setText("");
                                tvType.setText("");
                                EqpIdList.clear();
                                new Handler().postDelayed(() -> {
                                    lotID.requestFocus();
                                }, 500);

                            }
                        }).show(getSupportFragmentManager(),"DIALOG");
                    }else{

                        showToast("下架成功", true);
                        lotID.setText("");
                        tvStepName.setText("");
                        tvEqpId.setText("");
                        tvType.setText("");
                        EqpIdList.clear();
                        new Handler().postDelayed(() -> {
                            lotID.requestFocus();
                        }, 500);

                    }
                }
            }

            @Override
            public void onError(Response<ResponseBean<LockersTakenOffShelvesBean>> response) {
                super.onError(response);
                loadError(response.getException(), "MLOTAPPLYOUT");
            }
        });

    }

    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        return new FreeUI_AddViewEntity("header",llMain);
    }
}